/**
 * 新天气服务 - 使用更详细的天气API
 * API: http://t.weather.itboy.net/api/weather/city/101190101
 */

export interface WeatherForecast {
  date: string;
  high: string;
  low: string;
  ymd: string;
  week: string;
  sunrise: string;
  sunset: string;
  aqi: number;
  fx: string;
  fl: string;
  type: string;
  notice: string;
}

export interface WeatherData {
  message: string;
  status: number;
  date: string;
  time: string;
  cityInfo: {
    city: string;
    citykey: string;
    parent: string;
    updateTime: string;
  };
  data: {
    shidu: string;
    pm25: number;
    pm10: number;
    quality: string;
    wendu: string;
    ganmao: string;
    forecast: WeatherForecast[];
    yesterday: WeatherForecast;
  };
}

export class NewWeatherService {
  private static cache: {
    data: WeatherData | null;
    timestamp: number;
  } = { data: null, timestamp: 0 };

  private static readonly CACHE_DURATION = 10 * 60 * 1000; // 10分钟缓存
  private static readonly API_URL = '/api/weather/city/101190101'; // 南京 - 使用代理路径

  /**
   * 获取实时天气数据
   */
  static async getWeatherData(): Promise<WeatherData | null> {
    const now = Date.now();
    
    // 检查缓存
    if (this.cache.data && now - this.cache.timestamp < this.CACHE_DURATION) {
      console.log('🔄 使用缓存的天气数据');
      return this.cache.data;
    }

    try {
      console.log('🌐 正在获取新的天气数据...');
      
      const response = await fetch(this.API_URL, {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
        },
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data: WeatherData = await response.json();
      
      if (data.status !== 200) {
        throw new Error(`API error! message: ${data.message}`);
      }

      // 更新缓存
      this.cache = { data, timestamp: now };
      
      console.log('✅ 成功获取天气数据:', {
        城市: data.cityInfo.city,
        当前温度: data.data.wendu + '°C',
        湿度: data.data.shidu,
        空气质量: data.data.quality,
        'PM2.5': data.data.pm25,
        更新时间: data.time
      });

      return data;
    } catch (error) {
      console.error('❌ 获取天气数据失败:', error);
      return null;
    }
  }

  /**
   * 根据当前时间和天气数据计算实时温度
   */
  static calculateCurrentTemperature(weatherData: WeatherData): number {
    const hour = new Date().getHours();
    const today = weatherData.data.forecast[0];
    
    // 解析温度范围
    const highMatch = today.high.match(/(\d+)℃/);
    const lowMatch = today.low.match(/(\d+)℃/);
    const maxTemp = highMatch ? parseInt(highMatch[1]) : 30;
    const minTemp = lowMatch ? parseInt(lowMatch[1]) : 20;
    
    // 根据时间计算温度曲线
    let currentTemp: number;
    
    if (hour >= 0 && hour < 6) {
      // 凌晨0-6点：接近最低温度
      currentTemp = minTemp + (maxTemp - minTemp) * 0.1;
    } else if (hour >= 6 && hour < 12) {
      // 上午6-12点：逐渐升温
      const progress = (hour - 6) / 6;
      currentTemp = minTemp + (maxTemp - minTemp) * (0.3 + progress * 0.5);
    } else if (hour >= 12 && hour < 18) {
      // 下午12-18点：最热时段，13-15点达到峰值
      if (hour >= 13 && hour <= 15) {
        currentTemp = maxTemp - 0.5 + Math.sin((hour - 13) / 2 * Math.PI) * 0.5;
      } else if (hour === 12 || hour === 16) {
        currentTemp = maxTemp - 1;
      } else {
        currentTemp = maxTemp - 1.5;
      }
    } else {
      // 晚上18-24点：逐渐降温
      const progress = (hour - 18) / 6;
      currentTemp = maxTemp - (maxTemp - minTemp) * progress * 0.6;
    }
    
    // 添加小幅随机波动
    currentTemp += (Math.random() - 0.5) * 0.5;
    
    return Math.round(currentTemp * 10) / 10;
  }

  /**
   * 根据天气和温度计算湿度
   */
  static calculateCurrentHumidity(weatherData: WeatherData, currentTemp: number): number {
    const hour = new Date().getHours();
    const today = weatherData.data.forecast[0];
    
    // 基础湿度根据天气类型调整
    let baseHumidity = parseInt(weatherData.data.shidu.replace('%', ''));
    
    // 根据天气类型微调
    if (today.type.includes('雨')) {
      baseHumidity = Math.max(baseHumidity, 75);
    } else if (today.type.includes('晴')) {
      baseHumidity = Math.min(baseHumidity, 60);
    }
    
    // 温度与湿度的反向关系
    const tempHumidityFactor = Math.max(0.8, Math.min(1.2, (35 - currentTemp) / 15));
    
    // 时间因素：午后湿度相对较低
    const timeHumidityFactor = hour >= 12 && hour <= 16 ? 0.95 : 1.05;
    
    const calculatedHumidity = Math.round(baseHumidity * tempHumidityFactor * timeHumidityFactor);
    
    return Math.max(30, Math.min(95, calculatedHumidity));
  }

  /**
   * 生成24小时温度趋势数据
   */
  static generate24HourTemperatureTrend(weatherData: WeatherData): Array<{name: string, value: number, time: string}> {
    const today = weatherData.data.forecast[0];
    
    // 解析温度范围
    const highMatch = today.high.match(/(\d+)℃/);
    const lowMatch = today.low.match(/(\d+)℃/);
    const maxTemp = highMatch ? parseInt(highMatch[1]) : 30;
    const minTemp = lowMatch ? parseInt(lowMatch[1]) : 20;
    
    const currentHour = new Date().getHours();
    
    return Array.from({ length: 24 }, (_, i) => {
      // 计算实际小时（从当前时间开始的24小时）
      const actualHour = (currentHour + i) % 24;
      
      let baseTemp: number;
      
      if (actualHour >= 0 && actualHour < 6) {
        // 凌晨0-6点：最低温度期
        baseTemp = minTemp + (maxTemp - minTemp) * 0.1;
      } else if (actualHour >= 6 && actualHour < 12) {
        // 上午6-12点：逐渐升温
        const progress = (actualHour - 6) / 6;
        baseTemp = minTemp + (maxTemp - minTemp) * (0.3 + progress * 0.5);
      } else if (actualHour >= 12 && actualHour < 18) {
        // 下午12-18点：最热时段
        if (actualHour >= 13 && actualHour <= 15) {
          baseTemp = maxTemp - 0.5 + Math.sin((actualHour - 13) / 2 * Math.PI) * 0.5;
        } else {
          baseTemp = maxTemp - 1;
        }
      } else {
        // 晚上18-24点：逐渐降温
        const progress = (actualHour - 18) / 6;
        baseTemp = maxTemp - (maxTemp - minTemp) * progress * 0.6;
      }
      
      // 添加小幅随机波动
      const finalTemp = baseTemp + (Math.random() - 0.5) * 0.5;
      
      return {
        name: '温度',
        value: Math.round(finalTemp * 10) / 10,
        time: `${(currentHour + i) % 24}:00`
      };
    });
  }

  /**
   * 计算空气质量指数
   */
  static getAirQualityIndex(weatherData: WeatherData): number {
    const aqi = weatherData.data.forecast[0]?.aqi || 50;
    return Math.max(20, Math.min(300, aqi));
  }

  /**
   * 计算UV指数
   */
  static calculateUVIndex(weatherData: WeatherData): number {
    const hour = new Date().getHours();
    const today = weatherData.data.forecast[0];
    
    // 夜间UV指数为0
    if (hour < 6 || hour > 18) {
      return 0;
    }
    
    // 基础UV指数
    let baseUV = 7;
    
    // 根据天气类型调整
    if (today.type.includes('晴')) {
      baseUV = 9;
    } else if (today.type.includes('云') || today.type.includes('阴')) {
      baseUV = 5;
    } else if (today.type.includes('雨')) {
      baseUV = 3;
    }
    
    // 根据时间调整（正午最强）
    const timeMultiplier = Math.sin((hour - 6) / 12 * Math.PI);
    const uvIndex = baseUV * timeMultiplier;
    
    return Math.round(uvIndex * 10) / 10;
  }
}
